package com.huxiaohui.ssbx.agent.openapp;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.huxiaohui.ssbx.agent.BaseAgent;
import com.huxiaohui.ssbx.agent.prompt.PromptManagement;
import com.huxiaohui.ssbx.config.ModelConfig;
import com.huxiaohui.ssbx.constants.PromptConstants;
import com.huxiaohui.ssbx.constants.ResponseConstants;
import com.huxiaohui.ssbx.service.IVoiceService;
import com.huxiaohui.ssbx.utils.ResponseFutureHolder;
import com.huxiaohui.ssbx.utils.SessionHolder;
import com.huxiaohui.ssbx.utils.SessionMessage;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.socket.TextMessage;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;

@Slf4j
public class OpenAppAgent extends BaseAgent {

    @Resource(name = ModelConfig.MAIN_AGENT)
    private ChatModel chatModel;
    @Resource
    private PromptManagement promptManagement;

    private final String sessionId;

    public OpenAppAgent(String sessionId) {
        this.sessionId = sessionId;
    }

    @Override
    protected String solve(String task) {
        // 调用大模型生成JSON数据
        Map<String, String> params =  Map.of(PromptConstants.TASK, task);
        String prompt = StrUtil.format(this.promptManagement.getPrompt(PromptConstants.OPEN_APP_SYSTEM), params);

        boolean flag = true;
        String json = "";
        String requestId = IdUtil.fastSimpleUUID();
        Map<String,Object> result = new HashMap<>(Map.of("requestId", requestId));
        while (flag) {
            try {
                json = this.chatModel.call(prompt);
                JSONUtil.parseArray(json);  // 校验JSON格式是否正确
                result.put("task", json);
                json = JSONUtil.toJsonStr(result);
                flag = false;
            } catch (Exception e) {
                String format = "这是你上次生成的JSON数据：{} \nJSON格式存在错误：{} \n请根据下面要求重新生成纯JSON格式。\n{}";
                prompt = StrUtil.format(format, json, e.getMessage(), prompt);
            }
        }

        // 创建CompletableFuture用于阻塞和接收结果
        CompletableFuture<String> future = new CompletableFuture<>();
        ResponseFutureHolder.put(requestId, future);

        try {
            // 通过session发送信息给客户端
            SessionMessage.sendMessage(SessionHolder.get(this.sessionId), json, ResponseConstants.OPEN_APP);
            return future.get();
        } catch (Exception e) {
            log.debug("处理OpenAppAgent失败", e);
        } finally {
            ResponseFutureHolder.remove(requestId);
        }

        return "处理失败！";
    }

    @Override
    public ChatModel chatModel() {
        return this.chatModel;
    }
}
